import React, { useEffect, useState } from 'react';
import {
  Table, Modal, Form, Input, Col, message, Switch, Select,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  handleSupplier,
} from '@/services/goodCenter/invoicing';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils';

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    align: 'center',
    key: 'index',
  },
  {
    title: '类型名称',
    align: 'center',
    key: 'name',
  },
  {
    title: '创建时间',
    align: 'center',
    key: 'createTime',
  },
];

const roomType = props => {
  const { getFieldDecorator } = props.form;
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [staffList, setStaffList] = useState([]);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const [info, setInfo] = useState({});
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);
  const [confirmLoading, setconfirmLoading] = useState(false);

  // 列表
  const getList = async params => {
    const r = await handleSupplier(params, 'GET');
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
  };
  useEffect(() => {
    getList(listQuery);
  }, [listQuery]);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };

  const removeRole = async record => {
    handleSupplier({
      id: record.id,
    }, 'DELETE').then(res => {
      if (res.data.code === '0') {
        const index = data.findIndex(e => e.id === record.id);
        setColData(() => {
          data.splice(index, 1);
          return [...data];
        });
      }
    })
  };
  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      setInfo(record)
    }
  };
  // 查询表单
  const getFields = () => (
    <Col span={18}>
      <Col span={8}>
        <Form.Item label="类型名称">
          <Input onChange={v => { setListQuery({ ...listQuery, name: v.target.value }) }} placeholder="类型名称" value={listQuery.name} />
        </Form.Item>
      </Col>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      console.log(values)
      if (!err) {
        let med = 'POST'
        if (values.id) {
          med = 'PUT'
        }
        setconfirmLoading(true)
        handleSupplier({ storeBusiness: values }, med).then(() => {
          getList(listQuery)
          setState(!isShow);
          setconfirmLoading(false)
        }).catch(() => {
          setconfirmLoading(false)
        })
      }
    });
  };
  // 清空查询条件
  const handleReset = () => {
    const aobj = {
      pageNo: 1,
      pageSize: 10,
    }
    setListQuery(aobj)
    getList(aobj)
  };
  // 按钮逻辑
  const handleBtn = type => {
    if (record.length !== 1 && type !== 1) return message.warning('请勾选一条数据！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      // 查询
      case 2:
        return handleSearch();
      case 3:
        return handleStatus(record[0]);
      // 删除
      case 4:
        return removeRole(record[0]);
      default:
        return ''
    }
  };
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : data} rowSelection={rowSelection} rowKey={record => record.id} />
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        confirmLoading={confirmLoading}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="类型名称">
            {getFieldDecorator('name', {
              initialValue: info.name,
              rules: [
                {
                  required: true,
                  message: '请输入类型名称',
                },
              ],
            })(<Input placeholder="请输入类型名称" />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(roomType));
